<?php

namespace addons\booking\model;

use think\Model;
use addons\booking\library\IntCode;

class UserCoupon extends Model
{

    // 表名
    protected $name = 'booking_user_coupon';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'is_used_text'
    ];


    public function getIsUsedList()
    {
        return ['1' => __('Is_used 1'), '2' => __('Is_used 2')];
    }


    public function getIsUsedTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_used']) ? $data['is_used'] : '');
        $list = $this->getIsUsedList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 检查优惠券的归属用户和是否已使用
     *
     * @param int $user_coupon_id
     * @param int $user_id
     * @return Object
     */
    public function checkUserOrUse($user_coupon_id, $user_id)
    {
        $row = $this->where('id', $user_coupon_id)->where('user_id', $user_id)->find();
        if (!$row) {
            throw new \Exception('未领取该优惠券或不可用！');
        }
        if ($row['is_used'] == 2) {
            throw new \Exception('该优惠券已使用！');
        }
        return $row;
    }

    //我的优惠券列表
    public static function tableList($param)
    {
        $pageNum = 15;
        if (isset($param['num']) && !empty($param['num'])) {
            $pageNum = $param['num'];
        }
        return self::field('id,coupon_id,user_id,is_used,expire_time,begin_time,createtime')->with([
            'Coupon' => function ($query) {
                $query->field('id,name,result,result_data,alone_num,receive_times,mode,use_times');
            }
        ])->where(function ($query) use ($param) {
            $time = time();
            if (isset($param['is_used']) && !empty($param['is_used'])) {
                $query->where('is_used', $param['is_used']);
            }

            if (isset($param['user_id']) && $param['user_id'] != '') {
                $query->where('user_id', $param['user_id']);
            }

            if (isset($param['begin_time']) && !empty($param['begin_time'])) {
                $query->where('begin_time', '>', $time);
            }
            if (isset($param['expire_time']) && !empty($param['expire_time'])) {
                $query->where('expire_time', '<', $time);
            }

        })->order('createtime desc')->paginate($pageNum);
    }


    //我的可以使用的优惠券【过滤掉条件不符合的】
    public static function myHouseCoupon($user_id, $house_id, $store_id)
    {
        $conditions = CouponCondition::getHouseCondition($house_id, $store_id);
        $sql = "condition_ids IS NULL OR condition_ids=''";
        foreach ($conditions as $key => $item) {
            $item['id'] = (int)$item['id'];
            $sql .= " OR FIND_IN_SET('{$item['id']}',condition_ids)";
        }

        $time = time();
        //我的所有未使用的优惠券
        $list = self::with([
            'Coupon' => function ($query) use ($sql) {
                $query->field('id,name,result,result_data,alone_num,receive_times,mode,use_times')->where($sql);
            }
        ])->where('user_id', $user_id)
            ->where('is_used', 1)
            ->where('begin_time', '<', $time)
            ->where('expire_time', '>', $time)
            ->select();

        $data = [];
        foreach ($list as $item) {
            if (!empty($item['coupon'])) {
                $coupon = $item->coupon->toArray();
                $coupon['id'] = is_numeric($coupon['id']) ? IntCode::encode($coupon['id']) : $coupon['id'];
                $coupon['user_coupon_id'] = $item->id;
                $data[] = $coupon;
            }
        }
        return $data;
    }

    //我的可以使用的优惠券【过滤掉条件不符合的】
    public static function myGoodsCoupon($user_id, $goods_ids)
    {
        $conditions = CouponCondition::getGoodsCondition($goods_ids);
        $sql = "condition_ids IS NULL OR condition_ids=''";
        foreach ($conditions as $key => $item) {
            $item['id'] = (int)$item['id'];
            $sql .= " OR FIND_IN_SET('{$item['id']}',condition_ids)";
        }
        $time = time();
        //我的所有未使用的优惠券
        $list = self::with([
            'Coupon' => function ($query) use ($sql) {
                $query->field('id,name,result,result_data,alone_num,receive_times,mode,use_times')->where($sql);
            }
        ])->where('user_id', $user_id)
            ->where('begin_time', '<', $time)
            ->where('expire_time', '>', $time)
            ->where('is_used', 1)
            ->select();

        $data = [];
        foreach ($list as $item) {
            if (!empty($item['coupon'])) {
                $coupon = $item->coupon->toArray();
                $coupon['id'] = IntCode::encode($coupon['id']);
                $coupon['user_coupon_id'] = $item['id'];
                $data[] = $coupon;
            }
        }
        return $data;
    }


    public function Coupon()
    {
        return $this->hasOne('Coupon', 'id', 'coupon_id');
    }
}
